/*
	Copyright (c) 2010 <copyright holders>
	This source code is licensed under The MIT License,
	see the file LICENSE for details.
	*/

#include "ServerLogic.hpp"

#include <boost/lexical_cast.hpp>

#include "gen/netmsg.pb.h"

namespace spelprog2 {
namespace net {
namespace server_logic {

using namespace netmsg;


void PassOn::onAuthedMessage(MessagePtr msg, const NetMessageInfo & info)
{
    server_.postMsg(msg, info);
}


void HandleLogin::onMessage(MessagePtr msg, const NetMessageInfo & info)
{
    if (server_.getVars().getVar(info.origin, "logged_in") == "yes") {
        netlog << "Superfluous login message from user #" + boost::lexical_cast<std::string>(info.origin);
        return;
    }

    LoginRequest * const loginRequest = dynamic_cast<LoginRequest *>(msg.get());

    const std::string & serverPassword = server_.getVars().getVar(SERVER_ID, "password");
    const bool passwordMatches = serverPassword == "" || loginRequest->password() == serverPassword;

    
    if (passwordMatches) {
        netlog << "User #" + boost::lexical_cast<std::string>(info.origin) + " successfully joins";

        LoginReply loginReply;
        loginReply.set_accepted(true);
        loginReply.set_assignedid(info.origin); //user didn't know about this yet
        server_.sendToUser(loginReply, info.origin);

        server_.getVars().refreshToUser(info.origin);
        server_.getVars().setVar(info.origin, "logged_in", "yes");
        server_.getVars().setVar(info.origin, "name", loginRequest->username());
        server_.getVars().setVar(info.origin, "player", STRING_CAST(info.origin - 1)); //TODO: remove, for testing
    }
    else {
        netlog << "Rejecting user #" + boost::lexical_cast<std::string>(info.origin) + " due to bad password";

        LoginReply loginReply;
        loginReply.set_accepted(false);
        server_.sendToUser(loginReply, info.origin);
    }
}


void Authorizer::onMessage(MessagePtr msg, const NetMessageInfo & info)
{
    if (server_.getVars().getVar(info.origin, "logged_in") == "yes") {
        onAuthedMessage(msg, info);
    }
}


void HandleVarChange::onAuthedMessage(MessagePtr msg, const NetMessageInfo & info)
{
    ServerVarChange * const varChange = dynamic_cast<ServerVarChange *>(msg.get());

    //for now, allow user changing all his own vars (even adding new ones)
    //TODO: disallow some user changing some vars critical to correct server operation, and adding too many
    if (varChange->userid() != info.origin) {
        return;
    }

    server_.getVars().setVar(varChange->userid(), varChange->key(), varChange->value());
}


}; //namespace server_logic
}; //namespace net
}; //namespace spelprog2
